﻿// 版权所有：
// 文 件  名：Common.cs
// 功能描述：
// 创建标识：Seven Song(m.sh.lin0328@163.com) 2014/1/19 11:28:48
// 修改描述：
//----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using TimedTask.Tools;
//using Visifire.Charts;
using TimedTask.Models;
using MSL.Tool;
using MSL.Tool.Data;
using System.Security.AccessControl;
using System.Xml;
using System.Net;
using ZdfFlatUI;

namespace TimedTask
{
    public class Helper
    {
        private static System.Windows.Media.MediaPlayer _player = new System.Windows.Media.MediaPlayer();

        // 程序退出
        public static void ExitApp()
        {
            Helper.EndApp("img");
            Helper.EndApp("reg");

            App.Current.Dispatcher.Invoke(new Action(
                delegate
                {
                    NotifyIconHelper.Instance().Hide();
                    App.Current.Shutdown();
                }
            ), null);
        }

        /// <summary>
        /// 格式化网速
        /// </summary>
        /// <param name="speedBytes"></param>
        /// <returns></returns>
        public static string NetSpeedFormat(double speedBytes)
        {
            int speed = (int)(speedBytes / 1024f);
            if (speed < 1024)
            {
                return String.Format("{0}K/s", speed.ToString("0.0"));
            }
            else
            {
                return String.Format("{0}M/s", (speed / 1024).ToString("0.0"));
            }
        }

        /// <summary>
        /// 远程提取文件保存至服务器上(使用WebRequest)
        /// </summary>
        /// <param name="url">一个URI上的文件</param>
        /// <param name="savePath">文件保存在服务器上的全路径</param>
        public static bool DownloadFileByWebRequest(string url, string savePath)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();

                int fileSize = (int)response.ContentLength;
                int bufferSize = 102400;
                byte[] buffer = new byte[bufferSize];
                string dirPath = savePath.Substring(0, savePath.LastIndexOf(@"\") + 1);
                MSL.Tool.IOHelper.CreateFolder(dirPath);

                FileStream fileStream = File.Create(savePath, bufferSize);
                int bytesRead;

                do
                {
                    bytesRead = stream.Read(buffer, 0, buffer.Length);
                    fileStream.Write(buffer, 0, bytesRead);
                } while (bytesRead > 0);

                fileStream.Flush();
                fileStream.Close();
                stream.Flush();
                stream.Close();

                return File.Exists(savePath);
            }
            catch (Exception ex)
            {
                LogHelper.SaveErrorLog("下载文件出错", ex);
                return false;
            }
        }

        #region 进程

        /// <summary>
        /// 杀死进程
        /// </summary>
        /// <param name="proccessName">进程名</param>
        public static void EndApp(string proccessName)
        {
            if ((proccessName + "").Length == 0)
            {
                return;
            }
            foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
            {
                if (p.ProcessName == proccessName)
                {
                    try
                    {
                        p.Kill();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.SaveErrorLog("Common KillProccess", ex);
                    }
                }
            }
        }
        #endregion

        #region CMD

        /// <summary>
        /// 运行cmd命令
        /// </summary>
        /// <param name="command">cmd命令文本</param>
        public static void Run(string command)
        {
            if (String.IsNullOrEmpty(command))
                return;
            try
            {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                //p.StandardInput.WriteLine("shutdown -s -t 30 -c \"如果此时不想关机，就点击“取消关机”按钮！\"");
                p.StandardInput.WriteLine(command);
                p.StandardInput.WriteLine("exit");
                string strRst = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
            }
            catch (Exception ex)
            {
                LogHelper.SaveErrorLog("Common Run", ex);
            }
        }
        #endregion

        #region 饼状图
        /// <summary>
        /// 
        /// </summary>
        /// <param name="title">标题名称</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="valuex"></param>
        /// <param name="valuey"></param>
        //public static Chart CreatePie(string title, int width, int height, List<string> valuex, List<string> valuey)
        //{
        //    Chart chart = new Chart();
        //    chart.Width = width;
        //    chart.Height = height;
        //    chart.BorderThickness = new Thickness(1);//禁用边框
        //    //chart.Margin = new Thickness(100, 5, 10, 5);
        //    //title.Padding = new Thickness(0, 5, 5, 0);

        //    chart.ToolBarEnabled = true;//是否启用打印
        //    chart.ScrollingEnabled = true;//是否启用滚动
        //    chart.View3D = true;//3D效果显示

        //    chart.Titles.Add(new Title()//设置标题的名称
        //    {
        //        Text = title
        //    });
        //    DataSeries series = new DataSeries();//数据线
        //    series.RenderAs = RenderAs.Pie;//柱状Stacked 设置数据线的格式
        //    DataPoint point;// 设置数据点   
        //    for (int i = 0; i < valuex.Count; i++)
        //    {
        //        point = new DataPoint();
        //        point.AxisXLabel = valuex[i];// 设置X轴点   
        //        point.LegendText = "##" + valuex[i];

        //        point.YValue = double.Parse(valuey[i]);//设置Y轴点
        //        //point.MouseLeftButtonDown += new MouseButtonEventHandler(dataPoint_MouseLeftButtonDown);
        //        series.DataPoints.Add(point); //添加数据点 
        //    }

        //    chart.Series.Add(series); // 添加数据线到数据序列。
        //    return chart;
        //}

        #endregion

        #region 文件添加users，everyone用户组的完全控制权限

        /// <summary>
        /// 为文件添加users，everyone用户组的完全控制权限
        /// </summary>
        /// <param name="filePath"></param>
        public static void AddSecurityControll2File(string filePath)
        {

            //获取文件信息
            FileInfo fileInfo = new FileInfo(filePath);
            //获得该文件的访问权限
            System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
            //添加ereryone用户组的访问权限规则 完全控制权限
            fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
            //添加Users用户组的访问权限规则 完全控制权限
            fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            //设置访问权限
            fileInfo.SetAccessControl(fileSecurity);
        }

        #endregion

        #region 声音

        /// <summary>
        /// 文字转语音
        /// </summary>
        /// <param name="message">文字信息</param>
        /// <param name="speekType">声音类别 0：单词男声Sam,1:单词男声Mike,2:单词女声Mary,3:中文发音，如果是英文，就依单词字母一个一个发音</param>
        public static void Speek(string message)
        {
            try
            {
                //引入COM组件:Microsoft speech object Library
                //SpeechLib.SpVoice voice = new SpeechLib.SpVoice();
                //voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0);
                //voice.Speak(message, SpeechLib.SpeechVoiceSpeakFlags.SVSFlagsAsync);
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 停止播放声音
        /// </summary>
        public static void StopAudio()
        {
            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (_player != null)
                {
                    _player.Stop();
                    _player.Close();
                }
            }));
        }
        /// <summary>
        /// 播放声音
        /// </summary>
        /// <param name="soundName">声音名</param>
        public static void PalyAudio(string soundName, double volume)
        {
            if (String.IsNullOrEmpty(soundName) || soundName.Contains("无"))
                return;

            string path = Const.Audios[soundName].ToString();
            if (!File.Exists(path))
                return;
            /*
              SoundPlayer类特点
              1）仅支持.wav音频文件；
            2）不支持同时播放多个音频（任何新播放的操作将终止当前正在播放的）；
            3）无法控制声音的音量；
              if (path.EndsWith(".wav"))
              {
                  using (System.Media.SoundPlayer player = new System.Media.SoundPlayer(path))
                  {
                      player.Play();//播放波形文件
                  }
              }
            */
            if (_player != null)
            {
                StopAudio();
            }
            System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (path.EndsWith(".mp3") || path.EndsWith(".wma") || path.EndsWith(".wav"))
                {
                    try
                    {
                        _player = new System.Windows.Media.MediaPlayer();
                        _player.Open(new Uri(path));
                        _player.Volume = volume / 100;//大小为0~1.0
                        _player.Play();
                    }
                    catch (Exception ex)
                    {
                        LogHelper.SaveErrorLog("Core Common_PalyAudio", ex);
                    }
                }
            }));
        }

        #endregion

        #region 获得程序版本

        /// <summary>
        /// 获得程序版本
        /// </summary>
        /// <returns></returns>
        public static string GetVersion()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
        #endregion

        #region 显示器

        private const uint WM_SYSCOMMAND = 0x0112;
        private const uint SC_MONITORPOWER = 0xF170;
        private static readonly IntPtr HWND_HANDLE = new IntPtr(0xffff);
        [System.Runtime.InteropServices.DllImport("user32")]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, uint wParam, int lParam);

        /// <summary>
        /// 打开显示器
        /// </summary>
        public static void OpenMonitor()
        {
            // 2 为关闭显示器， －1则打开显示器
            SendMessage(HWND_HANDLE, WM_SYSCOMMAND, SC_MONITORPOWER, -1);
        }
        /// <summary>
        /// 关闭显示器
        /// </summary>
        public static void CloseMonitor()
        {
            // 2 为关闭显示器， －1则打开显示器
            SendMessage(HWND_HANDLE, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
        }
        #endregion

        #region 启动外部程序

        /// <summary>
        /// 启动外部Windows应用程序
        /// </summary>
        /// <param name="appName">应用程序路径名称</param>
        /// <returns></returns>
        public static bool StartApp(string appName)
        {
            return StartApp(appName, null, System.Diagnostics.ProcessWindowStyle.Normal);
        }

        /// <summary>
        /// 启动外部应用程序
        /// </summary>
        /// <param name="appName">应用程序路径名称</param>
        /// <param name="arguments">启动参数</param>
        /// <param name="style">进程窗口模式</param>
        /// <returns></returns>
        public static bool StartApp(string appName, string arguments, System.Diagnostics.ProcessWindowStyle style)
        {
            bool result = false;
            using (System.Diagnostics.Process p = new System.Diagnostics.Process())
            {
                p.StartInfo.FileName = appName;//exe,bat and so on
                p.StartInfo.WindowStyle = style;
                p.StartInfo.Arguments = arguments;
                try
                {
                    p.Start();
                    //p.WaitForExit();
                    //p.Close();
                    result = true;
                }
                catch
                {
                }
            }
            return result;
        }
        #endregion

        #region 传回阳历y年m月的总天数

        /// <summary>
        /// 传回阳历y年m月的总天数
        /// </summary>
        public static int GetDaysByMonth(int y, int m)
        {
            int[] days = new int[] { 31, DateTime.IsLeapYear(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
            return days[m - 1];
        }
        #endregion

        #region 多个匹配内容

        /// <summary>
        /// 多个匹配内容
        /// </summary>
        /// <param name="input">输入内容</param>
        /// <param name="pattern">表达式字符串</param>
        /// <param name="groupName">分组名, ""代表不分组</param>
        public static List<string> GetList(string input, string pattern, string groupName)
        {
            List<string> list = new List<string>();
            Regex re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);//| RegexOptions.IgnorePatternWhitespace
            MatchCollection mcs = re.Matches(input);
            foreach (Match mc in mcs)
            {
                if (groupName != "")
                {
                    list.Add(mc.Groups[groupName].Value);
                }
                else
                {
                    list.Add(mc.Value);
                }
            }
            return list;
        }

        /// <summary>
        /// 多个匹配内容
        /// </summary>
        /// <param name="input">输入内容</param>
        /// <param name="pattern">表达式字符串</param>
        /// <param name="groupIndex">第几个分组, 从1开始, 0代表不分组</param>
        public static List<string> GetList(string input, string pattern, int groupIndex)
        {
            List<string> list = new List<string>();
            Regex re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);
            MatchCollection mcs = re.Matches(input);
            foreach (Match mc in mcs)
            {
                if (groupIndex > 0)
                {
                    list.Add(mc.Groups[groupIndex].Value);
                }
                else
                {
                    list.Add(mc.Value);
                }
            }
            return list;
        }
        #endregion

        #region 信息提醒

        private static Notifiaction notifiaction = new Notifiaction();

        /// <summary>
        /// 默认错误提示
        /// </summary>
        /// <param name="message">显示消息</param>
        public static void AlertError(string message)
        {
            //ShowTip(TimedTask.Control.ShowTipType.Warning, message);

            notifiaction.AddNotifiaction(new NotifiactionModel()
            {
                Title = "错误",
                Content = message,
                NotifiactionType = EnumPromptType.Error
            });
        }
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="message">显示消息</param>
        public static void Alert(string message)
        {
            //ShowTip(TimedTask.Control.ShowTipType.Information, message);

            notifiaction.AddNotifiaction(new NotifiactionModel()
            {
                Title = "提示",
                Content = message,
                NotifiactionType = EnumPromptType.Info
            });
        }
        /// <summary>
        /// 提示警告信息
        /// </summary>
        /// <param name="message">显示消息</param>
        public static void AlertWarning(string message)
        {
            //ShowTip(TimedTask.Control.ShowTipType.Warning, message);
            notifiaction.AddNotifiaction(new NotifiactionModel()
            {
                Title = "警告",
                Content = message,
                NotifiactionType = EnumPromptType.Warn
            });
        }
        /// <summary>
        /// 提示成功信息
        /// </summary>
        /// <param name="message">显示消息</param>
        public static void AlertSuccess(string message)
        {
            //ShowTip(TimedTask.Control.ShowTipType.Ok, message);
            notifiaction.AddNotifiaction(new NotifiactionModel()
            {
                Title = "恭喜",
                Content = message,
                NotifiactionType = EnumPromptType.Success
            });
        }
        /// <summary>
        /// 提示确认信息
        /// </summary>
        /// <param name="title">窗口标题</param>
        /// <param name="message">显示消息</param>
        public static void AlertConfirm(string title, string message, Action callback)
        {
            AlertConfirm(title, message, callback, null);
        }
        /// <summary>
        /// 提示确认信息
        /// </summary>
        /// <param name="title">窗口标题</param>
        /// <param name="message">显示消息</param>
        public static void AlertConfirm(string title, string message, Action callback, Action cancelAction)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                var window = new Control.ShowTip(Control.ShowTipType.Confirm, title, message);
                window.btnAccept.Click += (sender, e) =>
                {
                    window.Close();
                    Loading1(callback, "正在处理...");
                    //callback.Invoke();
                };
                if (cancelAction != null)
                {
                    window.btnCancle.Click += (sender, e) =>
                    {
                        cancelAction();
                    };
                }
                window.MouseLeftButtonDown += (sender, e) =>
                {
                    if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
                        window.DragMove();
                };
                window.ShowDialog();
            }));
        }
        /// <summary>
        /// 信息提醒
        /// </summary>
        /// <param name="tipType">提醒类型</param>
        /// <param name="msg">信息</param>
        private static void ShowTip(TimedTask.Control.ShowTipType tipType, string msg)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
               {
                   Control.ShowTip tip = new Control.ShowTip(tipType, msg);
                   switch (tipType)
                   {
                       case TimedTask.Control.ShowTipType.Ok:
                           msg = (String.IsNullOrEmpty(msg) ? msg = "操作成功！" : msg);
                           break;
                       case TimedTask.Control.ShowTipType.Warning:
                           msg = (String.IsNullOrEmpty(msg) ? msg = msg = "操作失败！" : msg);
                           break;
                       case TimedTask.Control.ShowTipType.Error:
                           msg = (String.IsNullOrEmpty(msg) ? msg = msg = "操作失败！" : msg);
                           break;
                       case TimedTask.Control.ShowTipType.Information:
                       default: break;
                   }
                   tip.Show();
               }));
        }
        #endregion

        #region 加载进度条
        /// <summary>
        /// 加载进度条
        /// </summary>
        /// <param name="doWork">执行方法</param>
        /// <param name="msg">提示</param>
        public static void Loading1(Action doWork, string msg)
        {
            if (doWork == null)
                return;
            Control.Loading load = new Control.Loading(doWork);
            if (String.IsNullOrEmpty(msg))
                msg = "正在加载。。。";
            load.Msg = msg;
            load.Start();
            load.ShowDialog();
        }
        #endregion

        #region 弹出Pup窗口提醒
        /// <summary>
        /// 弹出Pup窗口提醒
        /// </summary>
        /// <param name="title">窗口标题</param>
        /// <param name="subject">提醒主题</param>
        /// <param name="msg">信息</param>
        public static void ShowPupUp(string title, string subject, string msg)
        {
            if (String.IsNullOrEmpty(title))
                title = "提醒";

            notifiaction.AddNotifiaction(new NotifiactionModel()
            {
                Title = title + ((subject + "").Length > 0 ? " —— " + subject : ""),
                Content = msg,
                NotifiactionType = EnumPromptType.Success
            });

            //System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
            //{
            //    //Control.PopUP pop = new Control.PopUP();
            //    //pop.Subject = subject;
            //    //pop.Msg = msg;
            //    //pop.PopTitle = title;
            //    //pop.Show();
            //}));
        }
        #endregion

        /// <summary>
        /// 监听配置文件变动
        /// </summary>
        //public void ConfigFileWatcher()
        //{
        //    FileSystemWatcher watcher = new FileSystemWatcher();
        //    watcher.Path = Const.StartPath;
        //    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite;
        //    // 只监控.config文件  
        //    watcher.Filter = "*.xml";
        //    // 添加事件处理器。  
        //    watcher.Changed += (s, e) =>
        //    {
        //        ReadConf();
        //    };
        //    // 开始监控。  
        //    watcher.EnableRaisingEvents = true;
        //}

        /// <summary>
        /// 读取系统配置文件
        /// </summary>
        public static void ReadConf()
        {
            ConfHelper config = new ConfHelper(Const.Config);
            if (!File.Exists(Const.Config))
            {
                Helper.AlertWarning("配置文件丢失！");
                Application.Current.Shutdown();
            }

            if (!File.Exists(Const.StartPath + "\\Task.db"))
            {
                Helper.AlertWarning("数据库文件丢失！");
                Application.Current.Shutdown();
                return;
            }
            //修改数据库文件访问权限
            String dbPath = Const.StartPath + "\\Task.db";
            Helper.AddSecurityControll2File(dbPath);

            //数据库配置
            MSL.Tool.Data.DbHelper.ConnectionString = string.Format(config.GetValue("Conn"), Const.StartPath + @"\");
            MSL.Tool.Data.DbHelper.DatabaseType = MSL.Tool.Data.DataBaseType.SQLite;
            DbHelper.Instance.Reset();//收缩数据库

            //备份数据库 .bak
            String bakPath = Const.StartPath + "\\Bak\\";
            String bakDbPath = bakPath + "Task_" + DateTime.Now.ToString("yyyy-MM-dd") + ".bak";//每天第一次打开备份 
            IOHelper.CreateFolder(bakPath);
            IOHelper.DeleteFiles(bakPath, new String[] { ".bak" }, 3);//删除 3 天前的备份文件 

            if (!File.Exists(bakDbPath))
            {
                //IOHelper.DeleteFile(bakDbPath);
                IOHelper.CopyFile(dbPath, bakDbPath);
            }

            try
            {
                Const.IsCheckTask = true;

                string minutes = config.GetValue("LockMinute");
                Const.AppBgImg = Const.StartPath + config.GetValue("AppBgImg");
                Const.LockBgImg = Const.StartPath + config.GetValue("LockBgImg");
                Const.MinToTray = config.GetValue("MinToTray") == "1" ? true : false;
                Const.ShowShutDownRemind = config.GetValue("ShowShutDownRemind") == "1" ? true : false;
                Const.ShutDownContent = config.GetValue("ShutDownContent");
                Const.LockMinute = minutes.Length == 0 ? 3 : Convert.ToInt32(minutes);
                Const.SaveLog = config.GetValue("SaveLog") == "1" ? true : false;
                Const.CityCode = config.GetValue("CityCode");

                if (!String.IsNullOrEmpty(Const.CityCode))
                {
                    Const.CityName = Const.CityCode.Split('|')[0];
                    Const.CityCode = Const.CityCode.Split('|')[1];
                }
                #region 多标签读取

                /*
                XmlNode node = config.GetXmlNode("Configuration/NewsTag");

                Const.NewsUrl = config.GetValue("NewsUrl");
                Const.NewsTag = new SortedList();
                string key = String.Empty;
                if (node != null && node.HasChildNodes)
                {
                    foreach (XmlElement v in node.ChildNodes)
                    {
                        key = v.Attributes["title"].InnerText;
                        if (Const.NewsTag.ContainsKey(key))
                            continue;

                        Const.NewsTag.Add(key, v.InnerText.Replace("<![CDATA[", "").Replace("]]>", ""));
                    }
                }*/
                #endregion

                if (Const.AppBgImg.IndexOf("\\Bg\\") < 0)
                    Const.AppBgImg = Const.StartPath + "\\Bg\\bg.jpg";
                if (Const.LockBgImg.IndexOf("\\Bg\\") < 0)
                    Const.LockBgImg = Const.StartPath + "\\Bg\\lock.jpg";
            }
            catch (Exception ex)
            {
                LogHelper.SaveErrorLog("MainWindow.xaml.cs Window_Loaded", ex);
            }
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <returns></returns>
        public static string GetQunueNo()
        {
            int iSeed = 10;
            Random ro = new Random(iSeed);
            long tick = DateTime.Now.Ticks;
            Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));

            return ran.Next().ToString();
        }
    }
}
